﻿using System.Collections.Generic;
using System.Data;

namespace smp.QueryDb.Structure
{
    public class Procedure
    {
        internal string Declaration { get; private set; }
        internal List<ProcedureParameter> Parameters { get; private set; }
        
        public Procedure(string name)
        {
            Declaration = string.Format("[{0}]", name);
            Parameters = new List<ProcedureParameter>();
        }

        public Procedure(string schemaName, string name)
        {
            Schema = schemaName;
            Declaration = string.Format("[{0}].[{1}]", schemaName, name);
            Parameters = new List<ProcedureParameter>();
        }

        public Procedure(string dataBaseName, string schemaName, string name)
        {
            Database = dataBaseName;
            Schema = schemaName;
            Declaration = string.Format("[{0}].[{1}].[{2}]", dataBaseName, schemaName, name);
            Parameters = new List<ProcedureParameter>();
        }

        internal string Database { get; private set; }
        internal string Schema { get; private set; }

        protected ProcedureParameter AddParameter(string name, DbType dataType)
        {
            return AddParameter(name, dataType, ParameterDirection.Input);
        }

        protected ProcedureParameter AddParameter(string name, DbType dataType, ParameterDirection direction)
        {
            if(Parameters.Find(x => x.Name == name) != null)
            {
                throw Helper.Error("Cannot add duplicate parameter with name {0} on procedure {1}",
                                   name,
                                   Declaration);
            }
            var parameter = new ProcedureParameter(name, dataType, direction);
            Parameters.Add(parameter);
            return parameter;
        }
    }
}